import DemoStudentTe from '@/service/Demo/DemoStudentTeAppService.js';
import WxUserInfo from '@/service/02WX/WxUserInfoAppService.js';
import WXUserFocus from '@/service/02WX/WXUserFocusAppService.js';
import Pay from '@/service/Pay/PayAppService.js';
import CommonApi from '@/service/00Pub/CommonApiAppService.js';
// #ifdef H5
import wx from "@/lib/weixin-js-sdk/index.js";
// #endif

// 负责公共api的处理
export default {
	autoPlayVideo(video){
		video.play();
		setTimeout(()=>{
			video.play();
		},2000);
		// wx.config({
		//     // 配置信息, 即使不正确也能使用 wx.ready
		//     debug: false,
		//     appId: '',
		//     timestamp: 1,
		//     nonceStr: '',
		//     signature: '',
		//     jsApiList: []
		// });
		// wx.ready(()=> {
		// 	video.play();
		// });
	},
	
	// 保存用户信息
	async saveUserInfo(dataIn, isShowLoading = true) {
		let res = await WxUserInfo.SaveUserInfo(dataIn, null, null, isShowLoading);
		return res;
	},
	// 关注用户
	async toggleFocusUser(focusUserGUID, isFocus) {
		const userInfo = getApp().globalData.userInfo;
		if (!userInfo) {
			this.goLogin();
		} else {
			const res = await WXUserFocus.ToggleFocusUser({
				userGUID: userInfo.id,
				focusUserGUID: focusUserGUID,
				isFocus: isFocus
			});
			if (res) {
				if (isFocus) {
					// 调用方法
					this.showMsg('关注成功');
				} else {
					// 调用方法
					this.showMsg('取关成功');
				}
				return res;
			}
		}
	},
	// https://lbs.qq.com/service/webService/webServiceGuide/webServiceGcoder
	async parseLocation(longitude, latitude) {
		let res = await CommonApi.GetLocation(longitude, latitude);
		return res;
	},
	// 获取上传后的路径
	async chooseGetFilePath() {
		let res = await uni.chooseImage({
			count: 1,
			sourceType: ['album'],
		});
		this.showLodaing();
		let filePath = await this.upLoadFile(res.tempFilePaths[0]);
		this.hideLodaing();
		return filePath;
	},
	// 上传图片
	async upLoadFile(tmpPath) {
		//上传图片
		let resUpload = await uni.uploadFile({
			url: getApp().globalData.picDomain,
			filePath: tmpPath,
			fileType: 'image',
			name: 'file',
		});
		return getApp().globalData.picDomain + JSON.parse(resUpload.data).path;
	},
	// 打开位置
	openLocation(longitude, latitude, name, address) {
		wx.openLocation({
			latitude: Number(latitude),
			longitude: Number(longitude),
			scale: 18,
			name: name,
			address: address,
			success(res) {},
			fail(err) {
				console.log(err);
			}
		})
	},
	// 微信分享处理
	async wxGetLocation(globalData = getApp().globalData) {
		if (globalData.VuePrototype.$util.isWxBrowser()) {
			await this.initWxJdk();
			wx.ready(() => {
				wx.getLocation({
					type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
					success: (res) => {
						globalData.setLocationInfo(res.longitude, res.latitude);
					},
					cancel: async (res) => {
						// 默认取浏览器的
						res = await uni.getLocation({
							type: 'gcj02',
							geocode: true
						});

						globalData.setLocationInfo(res.longitude, res.latitude);
					}
				});
			});
		} else {
			// 默认取浏览器的
			const res = await uni.getLocation({
				type: 'wgs84',
				geocode: true
			});
			if (res) {
				globalData.setLocationInfo(res.longitude, res.latitude);
			}
		}
	},
	async hideAllNonBaseMenuItem (){
		await this.initWxJdk();
		wx.hideAllNonBaseMenuItem();
	},
	async initWxJdk() {
		const url = encodeURIComponent(window.location.href);
		let res = getApp().globalData.locationWxHerfCache[url];
		if (!res) {
			res = await CommonApi.GetJsdkPackage({
				url: url
			}, null, null, false);
			getApp().globalData.locationWxHerfCache[url] = res;
		}

		if (res) {
			wx.config({
				debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
				appId: res.appId, // 必填，公众号的唯一标识
				timestamp: res.timestamp, // 必填，生成签名的时间戳
				nonceStr: res.nonceStr, // 必填，生成签名的随机串
				signature: res.signature, // 必填，签名
				openTagList: ['wx-open-launch-weapp'],
				jsApiList: [
					'onMenuShareAppMessage',
					'updateAppMessageShareData',
					'getLocation',
					'openLocation',
					'hideAllNonBaseMenuItem'
				] // 必填，需要使用的JS接口列表
			});
		}
	},

	// this.$cw.encryptTest();
	async encryptTest() {
		let res = await DemoStudentTe.UpdateByDto();
	},

	// 展示分享提示
	showWxTip() {
		getApp().globalData.VuePrototype.$util.showImg([
			`https://pic.cwyyt.cn/upload/00whtc/sendfriend.png`
		])
	},

	// 微信分享处理
	async wxShare(title, desc, logo =
		`https://pic.cwyyt.cn/upload/00whtc/fylogo.jpg?rnd=${new Date().getTime()}`) {
		await this.initWxJdk();
		let url = window.location.href;
		if (getApp().globalData.userInfo) {
			if (!url.includes('fromUserGUID')) {
				if (url.includes('?')) {
					url += `&fromUserGUID=${getApp().globalData.userInfo.id}`;
				} else {
					url += `?fromUserGUID=${getApp().globalData.userInfo.id}`;
				}
			}
		}

		wx.ready(() => {
			wx.updateAppMessageShareData({
				title: title, // 分享标题
				desc: desc, // 分享描述
				link: url, // 分享链接，当前页面地址
				imgUrl: logo, // 分享图标的链接
				type: "link", // 分享类型
				dataUrl: "", // 默认为空
				success: res => {}
			});
		});

		// const url = encodeURIComponent(window.location.href);
		// let res = await WxUser.GetJsdkPackage({
		// 	url: url
		// }, null, null, false);
		// if (res) {
		// 	wx.config({
		// 		debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
		// 		appId: res.appId, // 必填，公众号的唯一标识
		// 		timestamp: res.timestamp, // 必填，生成签名的时间戳
		// 		nonceStr: res.nonceStr, // 必填，生成签名的随机串
		// 		signature: res.signature, // 必填，签名
		// 		jsApiList: [
		// 			'onMenuShareAppMessage',
		// 			'updateAppMessageShareData'
		// 		] // 必填，需要使用的JS接口列表
		// 	});


		// }
	},

	/** 支付订单 列子：this.$cw.payOrder(11,'AD41C2FA-5A96-4389-08A3-08DAB2620DC1','开店码升级','/pages/10homeSub/partnerInfo/partnerInfo','/pages/10homeSub/rewardDistributionDecord/rewardDistributionDecord')
	 * @param {Object} productType 10 购买视频 11 获取购买
	 * @param {Object} productId 10 表示订单ID  11 开店码ID
	 * @param {Object} productName 产品名称
	 * @param {Object} objectId 对应其他ID
	 */
	async payOrder(productType, productId, productName, objectId) {
		let userInfo = getApp().globalData.userInfo;
		let data = {
			productDto: {
				productId: productId,
				productType: productType,
				productName: productName,
				objectId: objectId
			},
			openId: userInfo.openid,
			userGUID: userInfo.id
		};
		let result = await Pay.Order(data);
		return new Promise((resolve, reject) => {
			WeixinJSBridge.invoke('getBrandWCPayRequest', {
				"appId": result.appID, // 公众号名称，由商户传入
				"timeStamp": result.timeStamp, // 时间戳
				"nonceStr": result.nonceStr, // 随机串
				"package": result.package, // 扩展包
				"signType": "MD5", // 微信签名方式:MD5
				"paySign": result.paySign // 微信签名
			}, (res) => {
				if (res.err_msg == "get_brand_wcpay_request:ok") {
					uni.showToast({
						title: '支付查询中...',
						icon: 'loading',
						duration: 300000
					});
					let count = 0;
					const myInterval = setInterval(async () => {
						if (count > 15) {
							clearInterval(myInterval);
							uni.hideToast();
							this.showError('未找到支付订单');
							resolve(false);
						} else {
							// 支付查询
							const rdata = await Pay.OrderQuery({
								outTradeNo: result.outTradeNo
							}, null, null, false);
							if (rdata.isBuySuccess) {
								uni.hideToast();
								clearInterval(myInterval);
								resolve(true);
								this.showMsg('购买成功');
							} else {
								count++;
							}
						}
					}, 1500);
				} else if (res.err_msg ==
					"get_brand_wcpay_request:cancel") {
					this.showError('取消支付', 'none');
					resolve(false);
				} else {
					this.showError('支付失败', 'none');
					resolve(false);
				}
			});
		});
	},

	// 登陆微信
	async loginWx(redirect) {
		const fromUserGUID= getApp().globalData.VuePrototype.$store.state.vuex_fromUserGUID;
		const returnUrl = encodeURIComponent(
			`${window.location.origin}/pages/10home/home?redirect=${redirect||'/'}`);
		let resWx = await CommonApi.GetWxAuthorUrl({
			returnUrl: returnUrl,
			state: fromUserGUID?fromUserGUID:'code'
		});
		if (resWx) {
			window.location.replace(resWx);
		}
	},
	async refreshUserInfo(userId, globalData = getApp().globalData) {
		if(!userId) userId=globalData.userInfo.id;
		let res = await WxUserInfo.GetUserInfo({
			id: userId
		}, null, null, false);
		if (res) {
			globalData.VuePrototype.$storage.setAppUserInfo(res.data, globalData);
		}
	},
}